# -*- coding: utf8 -*-

import urllib2
from django.utils import simplejson
from puppy.model import Query, Response, Item
from puppy.service.Config import *

def search(query):
  """Search function for solr-lucene.

  Parameters:

  * query (puppy.model.OpenSearch.Query)

  Returns:

  * puppy.model.OpenSearch.Response

  Raises:

  * urllib2.URLError

  """

  def parse_yahoo_json(site, query, results):
    """Create a OpenSearch Response from Solr/Lucene results.

    We choose to ask for results in JSON format. This function simply loads the JSON into memory and creates an equivalent representation that is OpenSearch compliant.

    Parameters:

    * site (str): search engine name
    * query (str): query search terms (n.b. not a OpenSearch Query object)
    * results (dict): results from service

    Returns:

    * OpenSearch.Response

    """
    response = Response()
    response.title = "{0}: {1}".format(site, query)
    response.link = url
    response.description = "Search results for '{0}' at {1}".format(query, site)
    response.total_results = results['numFound']
    response.start_index = results['start']
    response.items_per_page = results['numFound']
    response.query = query
    for result in results['docs']:
      item = Item()
      item.title = result['title'][0]
      item.link = result['attr_stream_name'][0]
      item.description = result['attr_content'][0]
      response.items.append(item)
    return response


  pos = 1
  url = "http://localhost:8983/solr/select?q=attr_content:{1}&wt=json&start={1}".format(urllib2.quote(query.search_terms), str(pos))
  results = ''
  try:
    response = urllib2.urlopen(url)
    results = simplejson.load(response)
    return parse_yahoo_json('Solr/Lucene', query.search_terms, results['response'])
  except urllib2.URLError, e:
    print "Error in SearchService: Solr/Lucene search failed", e
